package com.stellar.circle.domain.sSchool.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.stellar.auth.api.dto.UserInfoDTO;
import com.stellar.circle.basic.entity.SSchool;
import com.stellar.circle.basic.entity.SSchoolAdmin;
import com.stellar.circle.basic.service.SSchoolAdminService;
import com.stellar.circle.basic.service.SSchoolService;
import com.stellar.circle.controller.admin.sSchool.vo.SSchoolRequestPageVO;
import com.stellar.circle.controller.admin.sSchool.vo.SSchoolRequestVO;
import com.stellar.circle.controller.admin.sSchool.vo.SSchoolResponseVO;
import com.stellar.circle.convert.SSchoolConvert;
import com.stellar.circle.domain.sSchool.SSchoolDomainService;

import com.stellar.circle.rpc.UserRPC;
import com.stellar.core.context.LoginContextHolder;
import com.stellar.web.core.bean.PageResult;
import com.stellar.web.core.enums.IsDeletedFlagEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 学校信息表领域服务实现
 *
 * @author Jqchan
 * @version 1.0
 * @date 2025-05-17 18:48:39
 */
@Slf4j
@Service
public class SSchoolDomainServiceImpl implements SSchoolDomainService {

    @Resource
    private SSchoolService sSchoolService;

    @Resource
    private SSchoolAdminService sSchoolAdminService;

    @Resource
    private UserRPC userRPC;

    @Override
    public PageResult<SSchoolResponseVO> page(SSchoolRequestPageVO requestPageVO) {
        PageResult<SSchoolResponseVO> pageResult = new PageResult<>();
        SSchool queryEntity = SSchoolConvert.INSTANCE.convert(requestPageVO);
        queryEntity.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());

        List<SSchool> entities = sSchoolService.page(queryEntity,
                requestPageVO.getStart(), requestPageVO.getPageSize());

        if (entities.isEmpty()) {
            return pageResult;
        }

        Long count = sSchoolService.count(queryEntity);
        List<SSchoolResponseVO> vos = SSchoolConvert.INSTANCE.convertEntityToRespList(entities);


        // 批量获取学校ID
        List<Long> schoolIds = vos.stream()
                .map(SSchoolResponseVO::getId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        // 批量处理管理员信息
        if (!schoolIds.isEmpty()) {
            processSchoolAdmins(vos, schoolIds);
        }

        pageResult.setResult(vos);
        pageResult.setTotal(count.intValue());
        return pageResult;
    }

    private void processSchoolAdmins(List<SSchoolResponseVO> vos, List<Long> schoolIds) {
        // 批量查询学校管理员
        List<SSchoolAdmin> admins = sSchoolAdminService.batchQueryBySchoolIds(schoolIds);

        if (CollectionUtils.isEmpty(admins)) return;

        // 关联管理员信息到学校VO
        vos.forEach(v -> {
            List<String> schoolAdmins = admins.stream()
                    .filter(admin -> admin.getSchoolId().equals(v.getId()))
                    .map(SSchoolAdmin::getRealName)
                    .collect(Collectors.toList());
            v.setSchoolAdmins(schoolAdmins);
        });

    }

    @Override
    public Boolean update(SSchoolRequestVO requestVO) {
        SSchool entity = SSchoolConvert.INSTANCE.convert(requestVO);
        return sSchoolService.update(entity) != 0;
    }

    @Override
    public Boolean delete(Long id) {
        SSchool entity = new SSchool();
        entity.setId(id);
        entity.setIsDeleted(IsDeletedFlagEnum.DELETED.getVal());
        return sSchoolService.update(entity) != 0;
    }

    @Override
    public Boolean insert(SSchoolRequestVO requestVO) {
        SSchool entity = SSchoolConvert.INSTANCE.convert(requestVO);
        return sSchoolService.insert(entity) != 0;
    }

    @Override
    public SSchoolResponseVO get(Long id) {
        SSchool entity = sSchoolService.queryById(id);
        SSchoolResponseVO schoolResponseVO = SSchoolConvert.INSTANCE.convert(entity);
        // 填充管理员
        SSchoolAdmin queryEntity = new SSchoolAdmin();
        queryEntity.setSchoolId(id);
        queryEntity.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
        List<SSchoolAdmin> sSchoolAdmins = sSchoolAdminService.queryAllByCondition(queryEntity);
        if (!CollectionUtils.isEmpty(sSchoolAdmins)) {
            List<String> schoolAdmins = sSchoolAdmins.stream()
                    .map(SSchoolAdmin::getRealName)
                    .collect(Collectors.toList());
            schoolResponseVO.setSchoolAdmins(schoolAdmins);
        }
        // 获取该校用户数量
        Long userCount = userRPC.countBySchoolId(id);
        schoolResponseVO.setUserCount(userCount);
        // 获取学校校区数量 - 当前逻辑通过学校名称统计
        SSchool countEntity = new SSchool();
        countEntity.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
        countEntity.setSchoolName(schoolResponseVO.getSchoolName());
        Long campusCount = sSchoolService.count(countEntity);
        schoolResponseVO.setCampusCount(campusCount);
        return schoolResponseVO;
    }

    @Override
    public List<SSchoolResponseVO> getSchoolListByLocation(Double longitude, Double latitude) {
        List<SSchool> sSchools = sSchoolService.getSchoolListByLocation(longitude, latitude);
        return SSchoolConvert.INSTANCE.convertEntityToRespList(sSchools);
    }

    @Override
    public List<SSchoolResponseVO> getSchoolListByUser() {
        Long userId = LoginContextHolder.getUserId();
        SSchoolAdmin queryEntity = new SSchoolAdmin();
        queryEntity.setAdminId(userId);
        queryEntity.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
        List<SSchoolAdmin> sSchoolAdmins = sSchoolAdminService.queryAllByCondition(queryEntity);
        if (!CollectionUtils.isEmpty(sSchoolAdmins)) {
            List<Long> schoolIds = sSchoolAdmins.stream()
                    .map(SSchoolAdmin::getSchoolId)
                    .collect(Collectors.toList());
            List<SSchool> sSchools = sSchoolService.batchQueryByIds(schoolIds);
            if (!CollectionUtils.isEmpty(sSchools)) {
                List<SSchoolResponseVO> sSchoolResponseVOS = SSchoolConvert.INSTANCE.convertEntityToRespList(sSchools);
                for (SSchoolResponseVO sSchoolResponseVO : sSchoolResponseVOS) {
                    // 获取该校管理员
                    SSchoolAdmin adminQueryEntity = new SSchoolAdmin();
                    adminQueryEntity.setSchoolId(sSchoolResponseVO.getId());
                    List<SSchoolAdmin> admins = sSchoolAdminService.queryAllByCondition(adminQueryEntity);
                    if (!CollectionUtils.isEmpty(admins)) {
                        List<String> schoolAdmins = admins.stream()
                                .map(SSchoolAdmin::getRealName)
                                .collect(Collectors.toList());
                        sSchoolResponseVO.setSchoolAdmins(schoolAdmins);
                    }
                    // 获取该校用户数量
                    Long userCount = userRPC.countBySchoolId(sSchoolResponseVO.getId());
                    sSchoolResponseVO.setUserCount(userCount);
                    // 获取学校校区数量 - 当前逻辑通过学校名称统计
                    SSchool countEntity = new SSchool();
                    countEntity.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
                    countEntity.setSchoolName(sSchoolResponseVO.getSchoolName());
                    Long campusCount = sSchoolService.count(countEntity);
                    sSchoolResponseVO.setCampusCount(campusCount);
                }
                return sSchoolResponseVOS;
            }
        }
        return Collections.emptyList();
    }
}
